import { reactive, ref, toRefs } from "vue";

type paginationParams = {
  pageNum: Number;
  pageSize: Number;
};

export default function useTable<
  T extends { list: any[]; total: number },
  P extends IProductParams
>(fn: (paramas: P) => RES<T>, searchParams?: Object) {
  const paramas = reactive({
    pageNum: 1,
    pageSize: 10,
  });
  const list = ref<T["list"]>([]);
  const total = ref(0);

  const fetch = () => {
    fn({ ...(paramas as P), ...searchParams }).then((res) => {
      if (res.code === 200) {
        list.value = res.data.list;
        total.value = res.data.total;
      }
    });
  };
  fetch();
  const pageChangeHandle = (item: IProductParams) => {
    fn({ ...(paramas as P), ...item }).then((res) => {
      if (res.code === 200) {
        list.value = res.data.list;
        total.value = res.data.total;
      }
    });
  };
  const pageSizeChangeHandle = (item: IProductParams) => {
    fn({ ...(paramas as P), ...item }).then((res) => {
      if (res.code === 200) {
        list.value = res.data.list;
        total.value = res.data.total;
      }
    });
  };
  const searchHandle = (item: IProductParams) => {
    fn({ ...(paramas as P), ...item }).then((res) => {
      if (res.code === 200) {
        list.value = res.data.list;
        total.value = res.data.total;
      }
    });
  };
  const reset = (item: IProductParams) => {
    fn({ ...(paramas as P), ...item }).then((res) => {
      if (res.code === 200) {
        list.value = res.data.list;
        total.value = res.data.total;
      }
    });
  };
  return {
    list,
    ...toRefs(paramas),
    total,
    pageChangeHandle,
    pageSizeChangeHandle,
    searchHandle,
    reset,
  };
}
